<template>
    <div class="Address">
<!--地址管理-->
        <h1>地址管理</h1>
        <table class="t-table" >
            <thead>
            <tr>
                <th v-for="(word,key) in cols" :key="key" v-text="word" />
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="item in rows" :key="item" >
                <td v-for="key in Object.keys(cols)" :key="key" v-text="item[key]" />
                <td ><button @click="remove(item)" >删除</button></td>
            </tr>
            <tr class="save" >
                <td v-for="(word,key) in cols" :key="key">
                    <input class="t-input" :maxlength="key === 'tel' ? 11 : 100" type="text" :placeholder="word" v-model="toSave[key]" />
                </td>
                <td ><button @click="save()" >保存</button></td>
            </tr>
            </tbody>
        </table>
    </div>
</template>

<script>
    export default {
        props: {
        },
        data(){
            return{
                cols:{name:'收件人',tel:'手机号码',address:'详细地址'},
                rows:[],
                toSave:{}
            }
        },
        created(){
            this.find();
        },
        methods:{
            find(){
                this.toSave = {};
                this.$axios.get('/address').then(res=>{
                    if (res.data.code === 200){
                        this.rows = res.data.content;
                    }else {
                        window.alert('服务异常，请稍后再试');
                    }
                });
            },

            save(){
                // 检查是否存在空值
                for (let key in this.cols){
                    if (! this.toSave[key]){
                        window.alert('请输入' + this.cols[key]);
                        return;
                    }
                }
                // 添加地址
                this.$axios.post('/address',this.toSave).then(this.$then).finally(this.find);
            },
            remove(item){
                this.$axios.delete('/address',{params:{id:item.id}}).then(this.$then).finally(this.find);
            }
        }
    };
</script>

<style scoped lang="scss" >
    @import "Address";
</style>
